import React, { useState, useEffect, useRef } from 'react';
import { useChartHook } from '@/hooks';
import * as echarts from 'echarts';

import './index.less';
export default function ChartPie() {
  const chartRef = useRef(null);
  const progressRef = useRef(null);
  const [pieChart, setPieChart] = useState(null);
  const [progressChart, setProgressChart] = useState(null);
  const [echartsInterval, setEchartsInterval] = useState(null);
  let currentEmphasisIndex = null;
  const data = [156, 180, 140, 126];

  useEffect(() => {
    renderPieChart();
  }, []);

  useEffect(() => {
    activeEcharts(-1);
  }, [pieChart]);

  const renderPieChart = () => {
    const option = getChartOption();
    let chartInstance = null;
    const chart = echarts.getInstanceByDom(chartRef.current);
    if (chart) {
      chartInstance = chart;
    } else {
      chartInstance = echarts.init(chartRef.current, 'dark');
    }
    setPieChart(chartInstance);
    chartInstance.setOption(option);
  };

  const activeEcharts = (currentIndex) => {
    // 数据长度
    let dataLength = 8;
    // 清空tooltip定时器
    clearTimeout(echartsInterval);
    // 加载tooltip定时器
    const interval = setTimeout(() => {
      pieChart.dispatchAction({
        type: 'downplay', //取消之前高亮的图形
        seriesIndex: 0,
        dataIndex: currentIndex,
      });

      // 获取当前显示第几个数据，从0 开始。（取 显示次数除以数据长度的余数）
      currentIndex = (currentIndex + 1) % dataLength;
      currentEmphasisIndex = currentIndex;
      // echarts的触发图表行为
      if (currentIndex % 2 !== 0) {
        activeEcharts(currentIndex);
      } else {
        pieChart.dispatchAction({
          type: 'highlight', //高亮当前图形
          seriesIndex: 0,
          dataIndex: currentIndex,
        });
        pieChart.dispatchAction({
          type: 'showTip', // 触发的行为
          seriesIndex: 0, // 触发的数据对应的坐标系（通常只有一个y轴，取0）
          dataIndex: currentIndex, // 第几个数据显示toolTip
        });

        activeEcharts(currentIndex);
      }
    }, 1000);
    setEchartsInterval(interval);
  };

  const width10 = (screen.width * 10) / 1920;

  const fontSize20 = (screen.width * 20) / 1920;
  const fontSize14 = (screen.width * 12) / 1920;
  const height20 = (screen.height * 20) / 1080;
  const height25 = (screen.height * 25) / 1080;
  const height28 = (screen.height * 28) / 1080;


  const getChartOption = () => {
    // 数据
    const optionList = {
      percentList: [1876, 850, 385, 154],
      typeList: ['设备1', '设备2', '设备3', '设备4'],
    };


    const color = ['#01AAF4', '#1FAEA3', '#F4C455', '#D66565'];
    const sum = optionList.percentList.reduce((per, cur) => per + cur, 0);
    const data = [];
    const gap = (1 * sum) / 100;
    const data1 = {
      value: optionList.percentList[0],
      name: optionList.typeList[0],
      label: {
        show: true,
        formatter: `{a|2938} 个\n{b|设备总数}`,
        rich: {
          a: {
            fontSize: fontSize20,
            color: '#F5B820',
            fontWeight: 600,
            lineHeight: height28,
            fontFamily: 'PingFangSC-Semibold, PingFang SC',
          },
          b: {
            fontSize: fontSize14,
            color: '#fff',
            fontWeight: 400,
            lineHeight: height20,
            fontFamily: 'PingFangSC-Regular, PingFang SC',
          },
          c: {
            fontSize: fontSize14,
            color: '#fff',
            fontWeight: 400,
            lineHeight: height20,
            fontFamily: 'PingFangSC-Regular, PingFang SC',
          },
        },
        fontSize: fontSize14,
        position: 'center',
        emphasis: {
          // 中间文字显示
          show: true,
        },
      },
    };
    const gapData = {
      name: '空格',
      value: gap,
      itemStyle: {
        color: 'transparent',
      },
    };

    for (let i = 0; i < optionList.typeList.length; i++) {
      if (i == 0) {
        data.push(data1);
      } else {
        data.push({
          name: optionList.typeList[i],
          value: optionList.percentList[i],
          itemStyle: {
            color: color[i],
          },
        });
      }

      data.push(gapData);
    }
    const option = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgb(0, 33, 82)',
        textStyle: {
          fontSize: fontSize14,
          color: 'white',
        },
        borderColor: '#4da0f8d6',
      },
      legend: {
        show: true,
        type: 'scroll',
        orient: 'vertical',
        height: '80%',
        left: '60%',
        top: 'center',
        icon: 'circle', //设置为圆，删除则为矩形
        itemWidth: width10,
        itemHeight: width10,
        itemGap: height25,
        data: optionList.typeList,
        formatter: function (name) {
          for (let i = 0; i < optionList.typeList.length; i++) {
            if (name == optionList.typeList[i]) {
              return `{name|${name}}{value0|${optionList.percentList[i]}}`;
              // return `{name|${name}}{value${i}|${percentList[i]}}`;
            }
          }
        },
        textStyle: {
          rich: {
            name: {
              fontSize: fontSize14,
              fontWeight: 400,
              height: 16,
              verticalAlign: 'top',
              padding: [4, 0, 0, 4],
              color: '#D1E5FF',
              fontFamily: 'Source Han Sans CN-Regular',
            },
            value0: {
              fontSize: fontSize20,
              fontWeight: 500,
              height: 16,
              width: 50,
              align: 'left',
              verticalAlign: 'top',
              padding: [5, 0, 0, 16],
              // color: '#0090ff',
              color: 'rgba(255, 188, 77, 1)',
              fontFamily: 'PangMenZhengDao',
            },
            value1: {
              fontSize: fontSize20,
              fontWeight: 500,
              height: 16,
              width: 50,
              align: 'left',
              verticalAlign: 'top',
              padding: [5, 0, 0, 16],
              color: '#3de2ff',
              fontFamily: 'PangMenZhengDao',
            },
          },
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['50%', '60%'],
          center: ['30%', '50%'],
          avoidLabelOverlap: false,
          left: '-8%',

          itemStyle: {
            borderColor: '#fff',
            borderWidth: 0,
          },
          label: {
            show: false,
          },
          labelLine: {
            show: false,
          },
          data: data,
        },
      ],
    };
    return option;
  };

  return (
    <div className="flex-cont1">
      {/* <img src={require('@/assets/index/pie_circle.png')} /> */}
      <div className="pie_chart" ref={chartRef}></div>
    </div>
  );
}
